import React, { useState } from 'react';
import { GetProp, message, Upload as AntdUpload, UploadProps } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import COS from 'cos-js-sdk-v5';
import './Upload.scss';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

/* 创建一个COS的实例 */
const cos = new COS({
  SecretId: 'AKIDEJFzav10kO2kMlxvfGjyBQWRCrQ0Vr3B',
  SecretKey: 'AHFyVu9HF3jZN86uY1OabY9oNqAXt7GF',
});

const Upload: React.FunctionComponent<{ staffPhoto: string, uploadStaffPhoto: (imageUrl: string) => void }> = ({ staffPhoto, uploadStaffPhoto }) => {
  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) message.error('请上传JPG或者PNG类型的文件!');
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) message.error('上传文件不能大于2MB!');
    return isJpgOrPng && isLt2M;
  };


  const customRequest = async (result: any) => {
    try {
      const response = await cos.uploadFile({ Bucket: 'wbepng-1321002078', Region: 'ap-nanjing', Key: result.file.name, Body: result.file, StorageClass: 'STANDARD' });
      const staffPhoto: string = `https://${response.Location}`;
      message.success('上传成功');
      uploadStaffPhoto(staffPhoto);
    } catch (e: any) {
      message.error('上传失败');
    }
  };

  return (
    <div>
      <AntdUpload customRequest={customRequest} beforeUpload={beforeUpload} name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false}>
        {staffPhoto ? <img src={staffPhoto} alt="avatar" style={{ width: '100%' }} /> : <PlusOutlined></PlusOutlined>}
      </AntdUpload>
    </div>
  );

};

export default Upload;
